package city.spring.modules.cardinfo.controller;

import city.spring.modules.cardinfo.entity.CardExpenseRecordEntity;
import city.spring.modules.cardinfo.entity.CardNumberEntity;
import city.spring.modules.cardinfo.service.CardExpenseRecordService;
import city.spring.modules.cardinfo.service.CardNumberService;
import city.spring.modules.cardinfo.vo.CardNumberEntityVO;
import city.spring.modules.consumptionItem.entity.ConsumptionItemsEntity;
import city.spring.modules.consumptionItem.service.ConsumptionItemsService;
import city.spring.modules.oldman.entity.OldmanInfoEntity;
import city.spring.modules.oldman.service.OldmanInfoService;
import city.spring.modules.personnel.entity.EmployeeEntity;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Controller：卡号管理
 *
 * @author Panxm
 * @date 2020-04-13 16:03:23
 */
@RestController
@RequestMapping("/card_elder")
public class CardNumberController extends ApiController {
    private final CardNumberService cardNumberService;
    private final EmployeeService employeeService;
    private final OldmanInfoService oldmanInfoService;
    private final CardExpenseRecordService cardExpenseRecordService;
    private final ConsumptionItemsService consumptionItemsService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<CardNumberEntity, ?>> entityOrderFields;

    public CardNumberController(CardNumberService cardNumberService, EmployeeService employeeService, OldmanInfoService oldmanInfoService, CardExpenseRecordService cardExpenseRecordService, ConsumptionItemsService consumptionItemsService) {
        this.cardNumberService = cardNumberService;
        this.employeeService = employeeService;
        this.oldmanInfoService = oldmanInfoService;
        this.cardExpenseRecordService = cardExpenseRecordService;
        this.consumptionItemsService = consumptionItemsService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(CardNumberEntity::getId);
        entityOrderFields.add(CardNumberEntity::getPerson);
        entityOrderFields.add(CardNumberEntity::getMemberCard);
        entityOrderFields.add(CardNumberEntity::getPhysicsCard);
        entityOrderFields.add(CardNumberEntity::getPersonType);
        entityOrderFields.add(CardNumberEntity::getOpeningTime);
        entityOrderFields.add(CardNumberEntity::getBalance);
        entityOrderFields.add(CardNumberEntity::getDepositBalance);
        entityOrderFields.add(CardNumberEntity::getStates);
        entityOrderFields.add(CardNumberEntity::getTotalConsumption);
        entityOrderFields.add(CardNumberEntity::getLastConsumption);
    }

    /**
     * 获取全部的 <strong>卡号管理</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, CardNumberEntity entity) {
        LambdaQueryChainWrapper<CardNumberEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<CardNumberEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        return success(page);
    }

    /**
     * 分页获取 <strong>老人的卡片信息列表</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping("oldcardInfo")
    public Object oldcardInfo(@PageableDefault Pageable pageable, CardNumberEntityVO entity) {
        QueryWrapper<? extends CardNumberEntity> queryWrapper = oldBuildQuery(entity);
        return success(cardNumberService.oldcardInfo(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 分页获取 <strong></strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping("old")
    public Object oldList(@PageableDefault Pageable pageable, CardNumberEntityVO entity) {
        QueryWrapper<? extends CardNumberEntity> queryWrapper = oldBuildQuery(entity);
        return success(cardNumberService.oldListPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    @GetMapping("staff")
    public Object staffList(@PageableDefault Pageable pageable, CardNumberEntityVO entity) {
        QueryWrapper<? extends CardNumberEntity> queryWrapper = staffBuildQuery(entity);
        return success(cardNumberService.staffListPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 获取一个 <strong>卡号管理</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        CardNumberEntity cardNumberEntity = cardNumberService.getById(id);
        try {
            if (cardNumberEntity.getPersonType().equals("内部员工") || cardNumberEntity.getPersonType().equals("外部员工")) {
                EmployeeEntity employeeEntity = employeeService.getById(cardNumberEntity.getPerson());
                cardNumberEntity.setPersonName(employeeEntity.getName());
            } else {
                OldmanInfoEntity oldmanBasisEntity = oldmanInfoService.getById(cardNumberEntity.getPerson());
                cardNumberEntity.setPersonName(oldmanBasisEntity.getOldmanName());
            }
        } catch (Exception ignore) {
            cardNumberEntity.setPerson(null);
            cardNumberEntity.setPersonName("");
        }
        return success(cardNumberEntity);
    }

    /**
     * 添加一个 <strong>卡号管理</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody CardNumberEntity entity) {
        cardNumberService.saveCardNumber(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 卡信息修改
     *
     * @param id
     * @param entity
     * @return
     */
    @PutMapping("/edit/{id}")
    public Object editCard(@PathVariable String id, @RequestBody CardNumberEntity entity) {
        entity.setId(id);
        cardNumberService.updateCardNumber(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 修改物理卡号
     *
     * @param id
     * @param entity
     * @return
     */
    @PutMapping("/editPhysics/{id}")
    public Object editPhysics(@PathVariable String id, @RequestBody CardNumberEntity entity) {
        entity.setId(id);
        cardNumberService.updatePhysics(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    /**
     * 删除一个 <strong>卡号管理</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        cardNumberService.deleteCardNumber(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>卡号管理</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        cardNumberService.deleteCardNumber(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 模拟消费
     */
    @PutMapping("cost/{id}")
    public Object cost(@PathVariable String id, @RequestBody CardExpenseRecordEntity cardExpenseRecordEntity) {
        CardNumberEntity cardNumberEntity = cardNumberService.getById(id);
        cardExpenseRecordEntity.setFlow("支出");
        ConsumptionItemsEntity consumptionItemsEntity = consumptionItemsService.getById(cardExpenseRecordEntity.getPayServiceId());
        cardNumberEntity.setTotalConsumption(cardNumberEntity.getTotalConsumption().add(cardExpenseRecordEntity.getNumber()).multiply(consumptionItemsEntity.getCost()));
        cardNumberEntity.setBalance(cardNumberEntity.getBalance().subtract(cardExpenseRecordEntity.getNumber().multiply(consumptionItemsEntity.getCost())));
        cardExpenseRecordEntity.setBalance(cardNumberEntity.getBalance());
        cardExpenseRecordService.saveCardExpenseRecord(cardExpenseRecordEntity, cardNumberEntity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 充值
     */
    @PutMapping("recharge/{id}")
    public Object recharge(@PathVariable String id, @RequestBody CardExpenseRecordEntity cardExpenseRecordEntity) {
        CardNumberEntity cardNumberEntity = cardNumberService.getById(id);
        cardExpenseRecordEntity.setFlow("充值");
        cardExpenseRecordEntity.setPayServiceId("1292372759450066946");
        ConsumptionItemsEntity consumptionItemsEntity = consumptionItemsService.getById(cardExpenseRecordEntity.getPayServiceId());
        cardNumberEntity.setBalance(cardNumberEntity.getBalance().add(cardExpenseRecordEntity.getNumber().multiply(consumptionItemsEntity.getCost())));
        cardExpenseRecordEntity.setBalance(cardNumberEntity.getBalance());
        cardExpenseRecordService.saveCardExpenseRecord(cardExpenseRecordEntity, cardNumberEntity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<CardNumberEntity> buildLambdaQuery(CardNumberEntity entity) {
        LambdaQueryChainWrapper<CardNumberEntity> lambdaQuery = cardNumberService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), CardNumberEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPerson()), CardNumberEntity::getPerson, entity.getPerson());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMemberCard()), CardNumberEntity::getMemberCard, entity.getMemberCard());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPhysicsCard()), CardNumberEntity::getPhysicsCard, entity.getPhysicsCard());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPersonType()), CardNumberEntity::getPersonType, entity.getPersonType());
        lambdaQuery.like(entity.getOpeningTime() != null, CardNumberEntity::getOpeningTime, entity.getOpeningTime());
        lambdaQuery.like(entity.getBalance() != null, CardNumberEntity::getBalance, entity.getBalance());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getStates()), CardNumberEntity::getStates, entity.getStates());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUsed()), CardNumberEntity::getUsed, entity.getUsed());
        lambdaQuery.like(entity.getTotalConsumption() != null, CardNumberEntity::getTotalConsumption, entity.getTotalConsumption());
        lambdaQuery.like(entity.getLastConsumption() != null, CardNumberEntity::getLastConsumption, entity.getLastConsumption());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容(老人)
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<? extends CardNumberEntity> oldBuildQuery(CardNumberEntityVO entity) {
        QueryWrapper<? extends CardNumberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getPersonName()), "t2.oldman_name", entity.getPersonName());
        wrapper.like(StringUtils.isNotBlank(entity.getTelephone()), "t2.telephone", entity.getTelephone());
        wrapper.like(StringUtils.isNotBlank(entity.getCertificate()), "t2.certificate", entity.getCertificate());
        wrapper.like(StringUtils.isNotBlank(entity.getPersonName()), "t2.oldman_name", entity.getPersonName());
        wrapper.like(StringUtils.isNotBlank(entity.getPersonType()), "t1.person_type", entity.getPersonType());
        wrapper.like(StringUtils.isNotBlank(entity.getMemberCard()), "t1.member_card", entity.getMemberCard());
        wrapper.like(StringUtils.isNotBlank(entity.getPhysicsCard()), "t1.physics_card", entity.getPhysicsCard());
        wrapper.eq(entity.getDepositBalance() != null, "t1.deposit_balance", entity.getDepositBalance());
        return wrapper;
    }

    /**
     * 构建查询条件内容(员工)
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<? extends CardNumberEntity> staffBuildQuery(CardNumberEntityVO entity) {
        QueryWrapper<? extends CardNumberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getPersonName()), "t2.name", entity.getPersonName());
        wrapper.like(StringUtils.isNotBlank(entity.getPersonType()), "t1.person_type", entity.getPersonType());
        wrapper.like(StringUtils.isNotBlank(entity.getMemberCard()), "t1.member_card", entity.getMemberCard());
        wrapper.like(StringUtils.isNotBlank(entity.getPhysicsCard()), "t1.physics_card", entity.getPhysicsCard());
        return wrapper;
    }

}
